<!--
 * @Author: ailin
 * @Date: 2022-12-08 17:22:25
 * @LastEditors: ailin
 * @LastEditTime: 2023-10-24 18:26:31
 * @Description: file content
 * @FilePath: /pay_platform/src/views/ule/setPay/setPayNumber.vue
-->
<template>
  <div class="container">
    <p class="title">{{ data.titleObj[data.pageStatus] }}</p>
    <div v-if="data.phoneNumber" class="phone_con">
      <p class="phone_tips">手机号码</p>
      <p class="phone_text">{{ plusXing(data.phoneNumber, 4, 3, 4) || "" }}</p>
    </div>
    <van-config-provider :theme-vars="themeVars">
      <van-form label-align="top" @submit="data.onSubmit">
        <van-cell-group inset>
          <van-field
            v-if="data.pageStatus != 'm'"
            v-model="data.validateCode"
            name="validateCode"
            label="验证码"
            placeholder="请输入验证码"
            type="digit"
            maxlength="6"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <template #right-icon>
              <div
                v-if="sendSms.smsStatus == 0"
                class="smsBtn"
                :data-stat="`获取验证码_${data.phoneNumber}`"
                @click="sendSms.sendSmsHandler"
              >
                {{ sendSms.hasSend ? "重新" : "" }}获取验证码
              </div>
              <div v-else class="smsBtn smsBtnDisabled">{{ sendSms.smsSecond }}s后重发验证码</div>
            </template>
          </van-field>
          <van-field
            v-if="data.pageStatus == 'm'"
            v-model="data.oldPassword"
            name="oldPassword"
            label="旧支付密码"
            type="password"
            placeholder="旧支付密码"
            clearable
            :rules="[{ required: true, message: '请输入旧支付密码' }]"
          />
          <van-field
            v-model="data.newPassword"
            name="newPassword"
            type="password"
            label="新支付密码"
            placeholder="请设置6位数字密码"
            clearable
            maxlength="6"
            :rules="[
              { required: true, message: '请输入新支付密码' },
              { pattern: /^\d{6}$/, message: '请设置6位数字密码' }
            ]"
          />
          <van-field
            v-model="data.password"
            name="password"
            type="password"
            label="确认支付密码"
            placeholder="请再次输入6位数字密码"
            clearable
            maxlength="6"
            :rules="[{ required: true, message: '请确认支付密码', validator: data.rePasswordFun }]"
          />
          <div v-if="data.pageStatus == 'm'" class="forgetPassword_con">
            <p class="forgetPassword" @click="data.toResetPassword">忘记旧密码？</p>
          </div>
        </van-cell-group>
        <div class="bottom_btn">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            color="#EE1919"
            :data-stat="`确认${data.pageStatus == 'm' ? '更新' : '设置'}支付密码`"
          >
            确认
          </van-button>
        </div>
      </van-form>
    </van-config-provider>
    <!-- <van-button round block type="primary" @click="data.loadScript" color="#EE1919"> 确认11 </van-button> -->
  </div>
</template>
<script setup>
import { onMounted, reactive } from "vue"
import { useRoute, useRouter } from "vue-router"
import { uleUrl, uleCdn, plusXing, changeSearch, loadScript, browser, setAppTitle, delLocalStorage } from "@/assets/js/common.js"
import { getSmsCode, setPayWord, updatePayWord, getMobileNum, sendCodeReset, resetPayPwd } from "@/assets/js/api/api.js"
import { showSuccessToast, showToast } from "vant"
import { encrypted } from "@/assets/js/DES.js"
const route = useRoute()
const router = useRouter()
const themeVars = reactive({
  "field-label-color": "#999999",
  "cell-font-size": "14px",
  "field-input-text-color": "#333",
  "field-placeholder-text-color": "#999",
  "cell-horizontal-padding": "0",
  "button-round-radius": "55px",
  "button-default-height": "45px"
})
const data = reactive({
  isOpenNewPay: null, //是否设置完成进行生物支付开通，1是其他不是
  pageStatus: "s", //设置密码s,修改密码m，重置密码r
  validateCode: "", //验证码
  oldPassword: "", //旧密码
  newPassword: "", //新密码
  password: "", //确认密码
  phoneNumber: "",
  titleObj: {
    s: "设置支付密码",
    m: "更新支付密码",
    r: "找回支付密码"
  },
  onSubmit: (values) => {
    console.log("submit", values)
    if (data.pageStatus == "s") {
      //设置支付密码
      setPayWord(
        {
          smsVerifyCode: encrypted(data.validateCode), // 短信验证码
          newPaymentPwd: encrypted(data.newPassword), // 新支付密码
          confirmPwd: encrypted(data.password) // 确认密码
        },
        "",
        "jsonCallback"
      ).then((res) => {
        console.log("=======res", res)
        if (res.code == "0000") {
          data.toSetPayPages()
        } else {
          showToast(res.msg)
        }
      })
    } else if (data.pageStatus == "m") {
      //修改支付密码
      updatePayWord(
        {
          smsVerifyCode: encrypted(data.validateCode), // 短信验证码
          newPaymentPwd: encrypted(data.newPassword), // 新支付密码
          oldPaymentPwd: encrypted(data.oldPassword), // 旧支付密码
          confirmPwd: encrypted(data.password) // 确认密码
        },
        "",
        "jsonCallback"
      ).then((res) => {
        console.log("=======res", res)
        if (res.code == "0000") {
          data.toSetPayPages()
        } else {
          showToast(res.msg)
        }
      })
    } else if (data.pageStatus == "r") {
      //找回支付密码
      resetPayPwd(
        {
          smsVerifyCode: encrypted(data.validateCode), // 短信验证码
          newPaymentPwd: encrypted(data.newPassword), // 新支付密码
          confirmPwd: encrypted(data.password) // 确认密码
        },
        "",
        "jsonCallback"
      ).then((res) => {
        console.log("=======res", res)
        if (res.code == "0000") {
          data.toSetPayPages()
        } else {
          showToast(res.msg)
        }
      })
    }
  },
  rePasswordFun: (val) => {
    if (val != data.newPassword) {
      return "两次密码不一致"
    }
  },
  //开通生物支付
  openPay: () => {
    loadScript("//i2.ulecdn.com/ulewap/j/cashierDesk/dsbridge.js", (res) => {
      try {
        dsBridge.call("openBiometricPay", function (ret) {
          //0 取消;1指纹失败次数过多;2成功
          console.log("openBiometricPay", ret)
          if (ret == 2) {
            showSuccessToast("开通成功")
            delLocalStorage("dontOpenPay") //清理缓存状态
            setTimeout(() => {
              dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
            }, 2000)
          } else if (ret == 1) {
            if (route.query.isSetting == 1) {
              showToast("多次验证错误，请稍后再试")
              setTimeout(() => {
                dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              }, 2000)
              return false
            }
            //开通失败通知收银台页面
            dsBridge.call("generalAction", {
              type: "6",
              ios_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              android_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              needlogin: "false",
              logTitle: ""
            })
          } else {
            //如果是app的设置页面进入的，验证完密码直接关闭当前webview页面,只有app进入此页面传参数setting=1
            if (route.query.isSetting == 1) {
              dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              return false
            }
            //开通失败通知收银台页面
            dsBridge.call("generalAction", {
              type: "6",
              ios_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              android_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              needlogin: "false",
              logTitle: ""
            })
            dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
          }
        })
      } catch (err) {
        console.log(err)
      }
    })
  },
  toResetPassword: () => {
    // location.href = `https://m.${uleUrl()}/muser/user/pd/toR?backurl=${encodeURIComponent(location.href)}`
    // let params={...route.query,...{status:'r'}}
    // router.replace(`/setPayNumber${changeSearch(params)}`)
    data.pageStatus = "r"
  },
  toSetPayPages: () => {
    //app下判断是否支持生物支付，支持则跳转生物支付设置提示页面，不支持则直接会到收银台页面
    if (browser().ule || browser().ylxd || browser().ylxdsq) {
      console.log("====app环境", browser(), data)
      loadScript("//i2.ulecdn.com/ulewap/j/cashierDesk/dsbridge.js", (res) => {
        if (data.isOpenNewPay == "1") {
          //需要开通生物支付时继续下一步
          //判断当前设备生物支付支持状态
          data.getBiometricStatus(function (res) {
            console.log("====当前支持的生物识别", res)
            //不支持app新方法直接返回收银台页面
            if (!res || !(res.isHardwareDetected && res.hasEnrolledFingerprints)) {
              //向收银台页面发送消息，通知收银台用户暂不开通生物支付并关闭当前webview
              dsBridge.call("generalAction", {
                type: "6",
                ios_action: JSON.stringify({
                  functionName: "NotifyTestPay",
                  functionParams: "noOpen"
                }),
                android_action: JSON.stringify({
                  functionName: "NotifyTestPay",
                  functionParams: "noOpen"
                }),
                needlogin: "false",
                logTitle: ""
              })
              // dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              showToast(`${data.titleObj[data.pageStatus]}成功`)
              setTimeout(() => {
                dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              }, 2000)
              return false
            } else {
              data.openPay()
            }
          })
        } else {
          //不需要开通生物支付时直接关闭当前页面
          showToast(`${data.titleObj[data.pageStatus]}成功`)
          setTimeout(() => {
            dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
          }, 2000)
          return false
        }
      })
    } else {
      console.log("====h5环境")
      showToast(`${data.titleObj[data.pageStatus]}成功`)
      setTimeout(() => {
        if (route.query.bakurl) {
          window.location.replace(route.query.bakurl)
        } else {
          window.history.go(-1)
        }
      }, 2000)
    }
  },
  getBiometricStatus: (callback) => {
    var hasMethod = dsBridge.hasNativeMethod("getBiometricStatus") //是否有当前方法
    if (!hasMethod) {
      return callback()
    }
    dsBridge.call("getBiometricStatus", function (ret) {
      //以json字符串返回
      // {
      // "isHardwareDetected":true, 手机硬件是否支持指纹 true 支持;false 不支持
      // "hasEnrolledFingerprints":true, 手机是否已注册指纹 true 已有指纹注册;false 无录入指纹
      // "isOpenOnThisPhone":true 当前用户是否在本机上开启的指纹支付 true 在本机上开启过;false 未在本机上开启

      // "isFingerPrinter": true,    true表示手机支持指纹 ，false 是面容
      // }
      console.log("getBiometricStatus", ret)
      callback && callback(JSON.parse(ret))
    })
  },
  getMobileNum: () => {
    getMobileNum({}, "", "jsonCallback").then((res) => {
      if (res.code == "0000") {
        data.phoneNumber = res.data
      } else {
        showToast(res.msg)
      }
    })
  }
})
//验证码发送功能
const sendSms = reactive({
  smsStatus: 0, //0未发送，1已发送
  smsSecond: 60, //倒计时
  hasSend: false, //是否发送过验证码
  sendSmsHandler: () => {
    console.log("sendSms.smsStatus", sendSms.smsStatus)
    if (data.pageStatus == "r") {
      //找回密码发送短信验证码
      sendCodeReset({}, "", "jsonCallback").then((res) => {
        console.log("=======res", res)
        if (res.code == "0000") {
          sendSms.smsStatus = 1
          sendSms.hasSend = true
          //请求发送短信接口，调用成功进行倒计时
          sendSms.timeOutFun()
        } else {
          showToast(res.msg || "验证码发送失败，请稍后重试")
        }
      })
    } else {
      getSmsCode({}, "", "jsonCallback").then((res) => {
        console.log("=======res", res)
        if (res.code == "0000") {
          sendSms.smsStatus = 1
          sendSms.hasSend = true
          //请求发送短信接口，调用成功进行倒计时
          sendSms.timeOutFun()
        } else {
          showToast(res.msg || "验证码发送失败，请稍后重试")
        }
      })
    }
  },
  timeOutFun: (callback) => {
    if (sendSms.smsSecond > 0) {
      setTimeout(() => {
        sendSms.smsSecond--
        sendSms.timeOutFun()
      }, 1000)
    } else {
      sendSms.smsStatus = 0
      sendSms.smsSecond = 60
    }
  }
})
onMounted(() => {
  console.log("地址参数1", route.query)
  data.pageStatus = route.query.status
  data.phoneNumber = route.query.mobile
  data.isOpenNewPay = route.query.isOpenNewPay
  // document.title = data.titleObj[data.pageStatus] || "设置支付密码"
  setAppTitle("支付密码")
  if (!data.phoneNumber) {
    data.getMobileNum()
  }
})
</script>
<style lang="scss" scoped>
.container {
  .title {
    font-size: 50px;
    color: #1e1f22;
    padding: 40px 0 46px 45px;
    line-height: 1;
  }
  .phone_con {
    margin: 21px 45px 0;
    padding-bottom: 27px;
    border-bottom: 1px solid #ebedf0;
    .phone_tips {
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 33px;
    }
    .phone_text {
      font-size: 28px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #1e1f22;
      line-height: 40px;
      margin-top: 20px;
    }
  }
  .smsBtn {
    font-size: 28px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ee1919;
    line-height: 40px;
  }
  .smsBtn:active {
    opacity: 0.8;
  }
  .smsBtnDisabled {
    color: #999999;
  }
  .forgetPassword_con {
    display: flex;
    justify-content: flex-end;
  }
  .forgetPassword {
    font-size: 28px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ee1919;
    line-height: 40px;
    margin-top: 20px;
    text-align: right;
  }
  .bottom_btn {
    padding: 82px 45px 0;
  }
}
:deep(.van-field__label--top) {
  font-size: 24px;
}
:deep(.van-cell-group--inset) {
  margin: 45px;
}
:deep(.van-cell:after) {
  left: 0;
  right: 0;
}
</style>
